from logging import getLogger

from nevow.athena import LiveElement, expose
from nevow.loaders import stan
from nevow import tags

from zope.component import getGlobalSiteManager

from meercat.job.interfaces import IJob



__all__ = ['JobStatus']

log = getLogger('meercat.server.nevow.elements.job')

registry = getGlobalSiteManager()

class JobStatus(LiveElement):
    jsClass = u'Meercat.Job.Status'
    
    def __init__(self, job, name, *args, **kwargs):
        super(JobStatus, self).__init__(*args, **kwargs)
        self._job = IJob(job)
        self._name = name
    
    @property
    def docFactory(self):
        return stan(tags.div(class_='yui-g',
                             render=tags.directive('liveElement'))[
            tags.h1()['Job Status'],
            tags.ul(class_='JobStatusActions actionList')[
                tags.li()[
                    tags.a(href='#',
                           onclick="Nevow.Athena.Widget.get(this).refresh(); return false;")['Refresh']],
                tags.li()[
                    tags.a(href='#',
                           onclick="Nevow.Athena.Widget.get(this).remove(); return false;")['Close']]],
            tags.h2()[self._name],
            tags.div(class_='jobStatus')])
    
    @expose
    def getStatus(self):
        log.info('%s.getJobStatus()' % (str(self),))
        return {u'running':self._job.isRunning(),
                u'status':self._job.getStatus()}
    
    @expose
    def getLinks(self):
        if self._job.isRunning():
            return [u'<a href="#" onclick="Nevow.Athena.Widget.get(this).stopJob(); return false;">Stop</a>']
        else:
            return [u'<a href="#" onclick="Nevow.Athena.Widget.get(this).startJob(); return false;">Start</a>',
                    u'<a href="#" onclick="Nevow.Athena.Widget.get(this).deleteJob(); return false;">Remove</a>']
    
    @expose
    def startJob(self):
        log.info('%s.startJob()' % (str(self),))
        assert not self._job.isRunning(), '%s is already running' % (self._name,)
        self._job.start()
        return True
    
    @expose
    def stopJob(self):
        log.info('%s.stopJob()' % (str(self),))
        assert self._job.isRunning(),'%s is not running' % (self._name,)
        self._job.stop()
        return True
    
    @expose
    def deleteJob(self):
        log.info('%s.deleteJob()' % (str(self),))
        assert not self._job.isRunning(), '%s is running. Running jobs cannot be removed' % (self._name,)
        
        self.page.getJobService().remove(self._job)
        registry.unregisterUtility(name=self._name, provided=IJob)
    